var io = require('socket.io').listen(8899);
var pg = require ('pg');

var con_string = 'tcp://dftg:Dftgodoopwd@localhost/dftg';

var pg_client = new pg.Client(con_string);
pg_client.connect();
var query = pg_client.query('LISTEN opportunity_changed');
var query = pg_client.query('LISTEN sale_order_line_change_changed');

io.sockets.on('connection', function (socket) {
	pg_client.query(`SELECT * FROM opportunity_stat_json;
					 SELECT * FROM so_line_change_stat_json`, function(err, result){
			var return_json = {'opportuntity': result.rows[0]['json_agg'], sale_order_line_change: result.rows[1]['json_agg']};
			console.log(return_json);
			socket.emit('connected', return_json);
		});

    socket.on('ready for data', function (data) {
        pg_client.on('notification', function(data) {
			console.log(data);
            socket.emit(data.channel, data.payload);
        });
    });
});